import axios from 'axios'
import qs from 'qs'
import router from '../router'
import req from './requrl'
axios.interceptors.request.use(
  config => {
    // if (localStorage.getItem('token')){
    //   config.headers['token'] = localStorage.getItem('token');
    // }
    return config;
  },
  error => {
    Message.error({
      message: '参数错误'
    })
  return Promise.reject(error);
});
axios.interceptors.response.use(
  response=>{
    if(response.headers.Authorization){
      localStorage.setItem('token',response.headers.Authorization);
    }
    if(response.data.code == 10011){
      router.push('/login');
    }
    return response;
  },
  err => {
    console.log(err)
  }
)
export default{
  install(Vue){
    var toastFn = function (content,width,type,that,time) {
      var that = that || this;
      that.$store.state.toast.showToast = true;
      that.$store.state.toast.content = content;
      that.$store.state.toast.type = type || 'warn';
      that.$store.state.toast.width = width || '7.6em';
      that.$store.state.toast.time = time || 700;
    }
    var findId = function(name,type){
      var coinList = JSON.parse(sessionStorage.getItem('CoinList'));
      for(var i = 0;i<coinList.length;i++){
        if(type){
          if(coinList[i].currency_id == name){
            return coinList[i];
          }
        }else{
          if(coinList[i].symbol == name){
            return coinList[i];
          }
        }

      }
    }
    var calcTime = function (data) {
      var obj = {};
      var date = Date.parse(new Date()) / 1000;
      obj.dateStart = date - data*24*60*60;
      obj.dateEnd = date;
      return obj;
    }
    var timeStramp = function (value,type) {
      var value = String(value).length>10?value:value*1000;
      var date = new Date(value);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + '-';
      var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
      var D = date.getDate()<10?'0'+date.getDate()+' ':date.getDate()+' ';
      var h = date.getHours()<10?'0'+date.getHours()+ ':':date.getHours() + ':';
      var m = date.getMinutes()<10?'0'+date.getMinutes():date.getMinutes();
      var s = date.getSeconds()<10?'0'+date.getSeconds():date.getSeconds();
      if(type == 'YY-MM-DD'){
        return Y+M+D;
      }else if(type == 'YY-MM-DD HH:MM'){
        return Y+M+D+h+m;
      }else{
        return Y+M+D+h+m+':'+ s;
      }
    }
    var needRes = ['to_email','captcha','login','password_reset','email','to_user','password_update','exports','add','set_asset_password','mobile','orders','to_mobile','buy','tradeorder','takeout','resetpwd','trade','register','carry'];
    Vue.prototype.regex = function(){//验证函数
      var obj = {
        phoneReg : /^[1][3,4,5,6,7,8,9][0-9]{9}$/,
        code:/^\d{4,6}$/,
        email:/^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/,
        pwd:/^[a-zA-Z0-9]{6,64}$/,//6-20位的密码
        exchangePwd:/^\d{6}$/,//6位数的交易密码
      }
      return obj;
    }
    Vue.prototype.findId = findId;
    Vue.prototype.service = function(url,params,type,tailParams){
      var that = this;
      if(localStorage.getItem('token')){
        params.token = localStorage.getItem('token')
      }
      if(type===undefined){
        type = 'get';
      }else{
        if(type!=='get'&&type!=='GET'&&type!=='post'&&type!=='POST'){
          tailParams = type;
        }
      }
      tailParams = tailParams?tailParams:'';
      if(type === 'post' || type === 'POST'){
        params = qs.stringify(params);
      }
      var urlReq;
      if(process.env.NODE_ENV === 'development'){
        urlReq = window.g.offline + req[url]+tailParams;
      }else if(process.env.NODE_ENV === 'production'){
        urlReq = window.g.ApiUrl + req[url]+tailParams;
      }
      if(type == 'post' || type == 'POST'){
        var axiosPromist = axios[type](urlReq,params)
      }else{
        var axiosPromist = axios[type](urlReq,{params:params})
      }
      return new Promise((resolve, reject) => {
        axiosPromist
          .then(response => {
            if(needRes.indexOf(url) == -1){
              if(response.data.code !== 200){
                this.loading(false);
                toastFn(response.data.msg,'','warn',that);
                if(response.data.code === 10011){
                  this.$router.push('/login')
                }
                return;
              }
            }
            resolve(response.data);
          }, err => {
            reject(err);
          })
          .catch((error) => {
            reject(error)
          })
      })
    }
    Vue.filter('timestamp',function (value,type) {
      return timeStramp(value,type)
    })
    Vue.filter('type',function (value) {
      if(value == 1){
        return '充币';
      }else{
        return '提币';
      }
    })
    Vue.filter('state',function (value) {
      if(value == 0){
        return '待处理';
      }else if(value == 1){
        return '审核通过';
      }else if(value == 2){
        return '审核未通过';
      }else if(value == 3){
        return '成功';
      }else if(value == 4){
        return '失败';
      }
    })
    Vue.filter('add',function (num1, num2, num3) {
      var baseNum, baseNum1, baseNum2,baseNum3;
      try {
        baseNum1 = num1.toString().split(".")[1].length;
      } catch (e) {
        baseNum1 = 0;
      }
      try {
        baseNum2 = num2.toString().split(".")[1].length;
      } catch (e) {
        baseNum2 = 0;
      }
      try {
        baseNum3 = num3.toString().split(".")[1].length;
      } catch (e) {
        baseNum3 = 0;
      }
      baseNum = Math.pow(10, Math.max(baseNum1, baseNum2,baseNum3));
      return (num1 * baseNum + num2 * baseNum + num3 * baseNum) / baseNum;
    })
    Vue.filter('sub',function (num1, num2, num3) {
      var baseNum, baseNum1, baseNum2;
      var precision;// 精度
      try {
        baseNum1 = num1.toString().split(".")[1].length;
      } catch (e) {
        baseNum1 = 0;
      }
      try {
        baseNum2 = num2.toString().split(".")[1].length;
      } catch (e) {
        baseNum2 = 0;
      }
      baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
      precision = (baseNum1 >= baseNum2) ? baseNum1 : baseNum2;
      return ((num1 * baseNum - num2 * baseNum) / baseNum).toFixed(precision);
    })
    Vue.filter('numDiv',function (num1, num2, num3) {
      var baseNum1 = 0, baseNum2 = 0;
      var baseNum3, baseNum4;
      try {
        baseNum1 = num1.toString().split(".")[1].length;
      } catch (e) {
        baseNum1 = 0;
      }
      try {
        baseNum2 = num2.toString().split(".")[1].length;
      } catch (e) {
        baseNum2 = 0;
      }
      baseNum3 = Number(num1.toString().replace(".", ""));
      baseNum4 = Number(num2.toString().replace(".", ""));
      return (baseNum3 / baseNum4) * Math.pow(10, baseNum2 - baseNum1)*100;
    })
    Vue.filter('time',function (during,type) {
        var during = during<0?0:during;
        let d = parseInt(during / (60 * 60 * 24));
        let dRest = during % (60 * 60 * 24);
        let h = parseInt(dRest / (60 * 60));
        let hRest = dRest % (60 * 60);
        let m = parseInt(hRest / 60);
        let mRest = hRest % 60;
        let s = mRest;
        if(type == 'day'){
          return d>=10?d:'0'+d
        }else if(type == 'hour'){
          return h>=10?h:'0'+h
        }else if(type == 'min'){
          return m>=10?m:'0'+m
        }else if(type == 'sec'){
          return s>=10?s:'0'+s
        }
        return (d>=10?d:'0'+d)+'天'+(h>=10?h:'0'+h)+'时'+(m>=10?m:'0'+m)+'分'+(s>=10?s:'0'+s)+'秒';
    })
    Vue.filter('level',function (data) {
      let tmpnewchar ='';
      switch (data){
        case 0: tmpnewchar = "零"; break;
        case 1: tmpnewchar = "一"; break;
        case 2: tmpnewchar = "二"; break;
        case 3: tmpnewchar = "三" ; break;
        case 4: tmpnewchar = "四" ; break;
        case 5: tmpnewchar = "五" ; break;
        case 6: tmpnewchar = "六" ; break;
        case 7: tmpnewchar = "七" ; break;
        case 8: tmpnewchar = "八" ; break;
        case 9: tmpnewchar = "九" ; break;
        case 10: tmpnewchar = "十" ; break;
       }
       return tmpnewchar;
    })
    Vue.filter('stateInvest',function (valve) {
      switch (valve){
        case 0:return '进行中';break;
        case 1:return '待结算';break;
        case 2:return '已结算';break;
        case 3:return '已退还';break;
      }
    })
    Vue.filter('sliceStr',function (value) {
      console.log(value)
      if(!value){
        return
      }
      var len = 15;
      if(value.length>len){
        return value.slice(0,len) + '...'
      }else {
        return value;
      }

    })
    Vue.prototype.toastFn = toastFn;
    Vue.prototype.calcTime = calcTime;
    Vue.prototype.loading = function (type) {
      this.$store.state.loading.show = type;
    };
  }
}

